package com.example.gkcircle.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.example.gkcircle.BaseActivity;
import com.example.gkcircle.R;
import com.example.gkcircle.library.object.GKUser;
import com.example.gkcircle.utils.ActivityUtil;
import com.example.gkcircle.utils.CommonUtil;
import com.example.gkcircle.utils.FileUtil;
import com.example.gkcircle.utils.MyAlertView;
import com.example.gkcircle.utils.MySVProgressHUD;
import com.example.gkcircle.utils.PicUtil;
import com.example.gkcircle.utils.StringUtil;
import com.example.gkcircle.utils.TextWatcherListener;
import com.example.gkcircle.utils.ThreadPoolUtils;
import com.example.gkcircle.utils.ToastFactory;

import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 发布失物招领页
 * Created by Jehu on 16/3/20.
 */
public class ComposeLostActivity extends BaseActivity implements View.OnClickListener {


    //ActionBar
    private ImageButton mBackBtn;
    private ImageButton mComposeBtn;
    private TextView mRightText;
    private TextView mLeftTextNum;
    private EditText mTelNumEdit;
    private EditText mContentEdit;
    private ImageView mAddPictureBtn;
    private ImageButton mDeletePicBtn;

    //调用相机和系统相册请求码
    private final int CAMERA_CODE=0;
    private final int GET_IMAGE_CODE=1;
    //压缩图片完成启程发布线程
    private Thread mCompressThread;
    //是否压缩完成
    private Boolean isFinishCompressed=false;
    //缩略图
    private Bitmap photo;
    //图片路径
    private String path;
    //压缩图片的路径
    private String tempPath;

    //失物、招领标识
    private final int LOST_FLAG=0;
    private final int FOUND_FLAG=1;
    private int flag;

    @Override
    protected void initView() {
        setContentView(R.layout.home_lost_compose_activity);
        mBackBtn = (ImageButton) this.findViewById(R.id.tabbar_left_btn);
        mComposeBtn = (ImageButton) this.findViewById(R.id.tabbar_right_btn);
        mLeftTextNum=(TextView)this.findViewById(R.id.home_lost_compose_left);
        mRightText = (TextView) this.findViewById(R.id.tabbar_right_text);
        mContentEdit = (EditText) this.findViewById(R.id.home_lost_compose_content);
        mTelNumEdit = (EditText) this.findViewById(R.id.home_lost_compose_tel_num);
        mAddPictureBtn = (ImageView) this.findViewById(R.id.home_lost_compose_add_picture);
        mDeletePicBtn=(ImageButton)this.findViewById(R.id.home_lost_delete_picture_btn);
    }

    @Override
    protected void initListener() {
        mBackBtn.setOnClickListener(this);
        mComposeBtn.setOnClickListener(this);
        mAddPictureBtn.setOnClickListener(this);
        mRightText.setOnClickListener(this);
        mDeletePicBtn.setOnClickListener(this);
        mContentEdit.addTextChangedListener(new TextWatcherListener(mLeftTextNum, mContentEdit, 100));
    }

    @Override
    protected void setData() {
        mDeletePicBtn.setVisibility(View.GONE);

        //设置ActionBar
        mBackBtn.setBackground(getResources().getDrawable(R.drawable.back_selector));
        mComposeBtn.setBackground(null);
        mRightText.setTextColor(getResources().getColor(R.color.main));
        mRightText.setBackground(getResources().getDrawable(R.drawable.transparent_to_grey));
        mRightText.setText(getResources().getString(R.string.home_lost_compose_lost));
        ActivityUtil.getInstance().addActivity(this);

        //接收intent数据设置布局
        Intent intent=getIntent();
        Bundle bundle=intent.getExtras();

        if(bundle==null)return;
        flag=bundle.getInt("flag");
        //失物布局
        if(flag==LOST_FLAG){
            mRightText.setText(getResources().getString(R.string.home_lost_compose_lost));
           mContentEdit.setHint(getResources().getString(R.string.home_lost_compose_lost_content_hint));
        //招领布局
        }else if(flag==FOUND_FLAG){
            mRightText.setText(getResources().getString(R.string.home_lost_compose_found));
            mContentEdit.setHint(getResources().getString(R.string.home_lost_compose_found_content_hint));
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tabbar_left_btn:
                quit(false);//false true都代表退出 方式不同
                break;
            case R.id.tabbar_right_text:
                AVUser user=AVUser.getCurrentUser();
                if(user==null){
                    ToastFactory.getToast(this,getResources().getString(R.string.not_login)).show();
                    ActivityUtil.startActivity(this, LoginActivity.class);
                    return;
                }

                final String telNum=mTelNumEdit.getText().toString().trim();
                final String content=mContentEdit.getText().toString().trim();
                if(telNum.isEmpty()){
                    MySVProgressHUD.getInstance(ComposeLostActivity.this).showInfoWithStatus(getResources().getString(R.string.no_contact));
                    return;
                }
                if(content.isEmpty()){
                    if(flag==LOST_FLAG){
                        MySVProgressHUD.getInstance(ComposeLostActivity.this).showInfoWithStatus(getResources().getString(R.string.no_lost_content));
                    }else{
                        MySVProgressHUD.getInstance(ComposeLostActivity.this).showInfoWithStatus(getResources().getString(R.string.no_lost_content));
                    }
                    return;
                }
                CommonUtil.hideSoftInputView(this);
                MySVProgressHUD.getInstance(ComposeLostActivity.this).showWithStatus(getResources().getString(R.string.home_lost_composing));

                if(path!=null && !path.isEmpty()){
                    //已压缩完发可发布
                    if(isFinishCompressed){
                        compose(telNum.trim(),content);
                        return;
                    }
                    //等待压缩图片完成的线程
                    mCompressThread=new Thread(new Runnable() {
                        @Override
                        public void run() {
                            compose(telNum.trim(),content);
                        }
                    });
                }else{
                    //无图片直接发布
                    compose(telNum.trim(),content);
                }
                break;
            case R.id.home_lost_compose_add_picture:
                if(path==null){
                    CommonUtil.hideSoftInputView(this);
                    new AlertView("上传相片", null, "取消", null, new String[]{"拍照", "从手机相册选择"}, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            switch (position){
                                case 0:
                                    ThreadPoolUtils.execute(new Runnable() {
                                        @Override
                                        public void run() {
                                            PicUtil.openCamera(ComposeLostActivity.this,CAMERA_CODE);
                                        }
                                    });
                                    break;
                                case 1:
                                    //调用相册
                                    ThreadPoolUtils.execute(new Runnable() {
                                        @Override
                                        public void run() {
                                            PicUtil.openAlbum(ComposeLostActivity.this, GET_IMAGE_CODE);
                                        }
                                    });
                                    break;
                            }
                        }
                    }).show();

                }else{
                    Intent intent=new Intent(this,PhotoViewAcitivty.class);
                    Bundle bundle=new Bundle();
                    bundle.putString("imagePath",path);
                    intent.putExtras(bundle);
                    this.overridePendingTransition(0,R.anim.zoom_in);
                    this.startActivity(intent);
                }
                break;
            case R.id.home_lost_delete_picture_btn:
                if(null!=path){
                    CommonUtil.hideSoftInputView(this);
                    MyAlertView.alertView=null;
                    MyAlertView.showAlertViewWithOKAndCancel(this, "是否移除图片?", new MyAlertView.IShowAlertViewWithOkAndCancelListener() {
                        @Override
                        public void onclickOk() {
                            mDeletePicBtn.setVisibility(View.GONE);
                            mAddPictureBtn.setBackground(ComposeLostActivity.this.getResources().getDrawable(R.mipmap.home_lost_add_picture_btn));
                            path=null;
                            tempPath=null;
                            isFinishCompressed=false;
                            //回收图片
                            if(!photo.isRecycled()){
                                photo.recycle();
                            }
                            //删除相片
                            FileUtil.deleteFile(FileUtil.MYPATHIMAGE + "tempImage.jpg");
                        }
                    });
                }
                break;
        }
    }

    private static OnCompressListener onCompressListener;
    private interface OnCompressListener{
        void complete();
    }

    //发布
    private void compose(final String telNum,final String content) {
        AVUser user=AVUser.getCurrentUser();
        if(flag==LOST_FLAG){
            final AVObject lost=new AVObject("Lost");
            lost.put("user",user);
            lost.put("contacts",telNum);
            lost.put("content",content);
            //添加图片
            if(path!=null && tempPath!=null){
                try {
                    AVFile file=AVFile.withAbsoluteLocalPath(StringUtil.filterPhotoName(path),tempPath);
                    lost.put("photo", file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    MySVProgressHUD.getInstance(ComposeLostActivity.this).showErrorWithStatus(getResources().getString(R.string.home_lost_compose_error));
                    return;
                }
            }
            lost.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    if(e==null){
                        if(tempPath!=null){
                            FileUtil.deleteFile(tempPath);
                        }
                        ComposeLostActivity.this.setResult(RESULT_OK);
                        finish();
                    }else{
                        Log.i("Compose", "done: "+e);
                        MySVProgressHUD.getInstance(ComposeLostActivity.this).showErrorWithStatus(getResources().getString(R.string.home_lost_compose_error));
                    }
                    MySVProgressHUD.getInstance(ComposeLostActivity.this).dismiss();
                }
            });

        }else{
            AVObject found=new AVObject("Found");
            found.put("user", user);
            found.put("contacts",telNum);
            found.put("content",content);
            //添加图片
            if(path!=null && tempPath!=null){
                try {
                    AVFile file=AVFile.withAbsoluteLocalPath(StringUtil.filterPhotoName(path),tempPath);
                    found.put("photo",file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    MySVProgressHUD.getInstance(ComposeLostActivity.this).showErrorWithStatus(getResources().getString(R.string.home_lost_compose_error));
                    return;
                }
            }
            found.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    if (e == null) {
                        if(tempPath!=null){
                            FileUtil.deleteFile(tempPath);
                        }
                        ComposeLostActivity.this.setResult(RESULT_OK);
                        finish();
                    } else {
                        MySVProgressHUD.getInstance(ComposeLostActivity.this).showErrorWithStatus(getResources().getString(R.string.home_lost_compose_error));
                    }
                    MySVProgressHUD.getInstance(ComposeLostActivity.this).dismiss();
                }
            });

        }
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!=RESULT_OK){
            FileUtil.deleteFile(FileUtil.MYPATHIMAGE+"tempImage.jpg");
            return;
        }
        switch (requestCode){
            case CAMERA_CODE:
                path=FileUtil.MYPATHIMAGE+"tempImage.jpg";
                break;
            case GET_IMAGE_CODE:
                photo=null;
                Uri photoUri = data.getData();        //获得图片的uri
                //ContentResolver resolver = getContentResolver();
                //photo = MediaStore.Images.Media.getBitmap(resolver, photoUri);
                //获取选取图书路径
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor cursor = managedQuery(photoUri, proj, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                //根据索引值获取图片路径
                path = cursor.getString(column_index);
                break;
        }
        int size=PicUtil.px2dip(this, 144);
        //获取缩略图
        photo=PicUtil.getImageThumbnail(path, size, size);
        //设置图片
        mAddPictureBtn.setBackground(PicUtil.bitmapToDrawble(photo,this));
        mDeletePicBtn.setVisibility(View.VISIBLE);

        //压缩图片回调方法
        ComposeLostActivity.onCompressListener=new OnCompressListener(){

            @Override
            public void complete() {
                //如果线程不为null 则启动发布线程
                if(mCompressThread!=null){
                    mCompressThread.start();
                }
            }
        };
        //开启压缩图片线程
        //压缩图片到100KB以下
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                //设置被压缩图片输出的路径
                tempPath = FileUtil.MYPATHIMAGE + StringUtil.filterPhotoName(path);
                //执行压缩
                PicUtil.compressedImageAndOut(path, tempPath);
                isFinishCompressed=true;
                //压缩完回调
                ComposeLostActivity.onCompressListener.complete();
            }
        });

    }

    private void quit(final boolean flag){
        CommonUtil.hideSoftInputView(this);
        boolean isNull=mContentEdit.getText()==null
                || mTelNumEdit.getText()==null
                || tempPath==null;
        boolean isEmpty=!mContentEdit.getText().toString().isEmpty()
                || !mContentEdit.getText().toString().isEmpty()
                || !mContentEdit.getText().toString().isEmpty();
        if (!isNull || isEmpty) {
            MyAlertView.alertView=null;
            MyAlertView.showAlertViewWithOKAndCancel(this, "正在编辑中,您确定要退出吗？", new MyAlertView.IShowAlertViewWithOkAndCancelListener() {
                @Override
                public void onclickOk() {
                    //用户不发布则删除相片
                    FileUtil.deleteFile(FileUtil.MYPATHIMAGE + "tempImage.jpg");
                    if (flag)ComposeLostActivity.super.onBackPressed();
                    else finish();
                }
            });
        }else{
            if(flag)super.onBackPressed();
            else finish();
        }
    }

    @Override
    public void onBackPressed() {
        quit(true);
    }
}